const app = getApp();
const _requsetCYZ = require('../../utils/requestData');
const _functionCYZ = require('../../utils/common.js');
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');// 引入SDK核心类
const qqmapsdk = new QQMapWX({ key: 'YDUBZ-ZHGC5-D65I6-QKTDH-PBM6E-SGF2M' });// 实例化API核心类
Page({
    data: {
        this_jinbi_pay_open:0,
		mianze_is_check:true,
        this_cate_id: 0,//分类ID
        this_top_config: null,
        this_cate_info: null,
        is_top: 0,
        img_count_limit: 6,//最多可上传图片的数量
        this_img_i: 0,
        this_img_max: 0,
        postimg: [],
        btn_submit_disabled: false,
        submitIsLoading: false,
        this_u_province: '',
        this_u_city: '',
        this_u_district: '',
        address: '',
        mobile:'',
        latitude: 0,
        longitude: 0,
        is_top: 0,
        top_day: 0,
        top_amount: 0,
        is_hongbao_open:false,
        is_wallet: 0,//是否发放红包
        is_wallet_avg: 0,//是否平均发放
        is_wallet_pwd: 0,//红包口令
    },
    onLoad: function (options) {
        var that = this;
        var cid = options.cid;
        var title = options.name;
        if (title) {
            wx.setNavigationBarTitle({ title: title + ' - 发布' });
        }
        if (!cid || cid < 0) {
            _functionCYZ.CYZ_alert('信息分类不存在', "index", "tab");
            return;
        }
        this.setData({ this_cate_id: cid });
        if (wx.getStorageSync("global_user_address")){
            that.setData({
                this_u_province: wx.getStorageSync("global_user_province"),
                this_u_city: wx.getStorageSync("global_user_city"),
                this_u_district: wx.getStorageSync("global_user_district"),
                address: wx.getStorageSync("global_user_address"),
                latitude: wx.getStorageSync("global_user_lat"),
                longitude: wx.getStorageSync("global_user_lng")
            });
        }else{
            that.getLocation();
        }
    },
    getLocation: function () {
        var that = this;
        _functionCYZ.CYZ_loading_n("定位中，请稍候...");
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: (res) => {
                        that.setData({
                            this_user_city: res.result.address_component.city,
                            this_u_lat: res.result.location.lat,
                            this_u_lng: res.result.location.lng
                        });
                        wx.setStorageSync('global_user_city', res.result.address_component.city);
                        wx.setStorageSync('global_user_address', res.result.address);
                        wx.setStorageSync('global_user_lat', res.result.location.lat);
                        wx.setStorageSync('global_user_lng', res.result.location.lng);
                        wx.setStorageSync('global_user_province', res.result.address_component.province);
                        wx.setStorageSync('global_user_city', res.result.address_component.city);
                        wx.setStorageSync('global_user_district', res.result.address_component.district);
                        that.setData({
                            this_u_province: res.result.address_component.province,
                            this_u_city: res.result.address_component.city,
                            this_u_district: res.result.address_component.district,
                            address: res.result.address,
                            latitude: res.result.location.lat,
                            longitude: res.result.location.lng
                        });
                    }
                });
            },
            fail: function () {
                //弹出系统设置
                wx.openSetting({
                    success: (res) => {
                        if (res.authSetting['scope.userLocation'] == false) {
                            wx.showModal({
                                title: '提示',
                                content: "请允许地理位置授权",
                                showCancel: false,
                                success: function () {
                                    that.getLocation();
                                }
                            });
                        } else {
                            that.getLocation();
                        }
                    }
                });
                return false;
            },
            complete: function () {
                wx.hideLoading();
            }
        })
    },
    onShow: function () {
        var that = this;
        app.checkUserGIsName();
        that.setData({ mobile: wx.getStorageSync('servers_mobile') });
        _functionCYZ.CYZ_loading();
        _requsetCYZ.cyz_requestGet('/Info/getCateInfo', { cate_id: that.data.this_cate_id }, function (xyz_data) {
            if (xyz_data.code == 1) {
                that.setData({ this_cate_info: xyz_data.info });
                //获取置顶配置
                _requsetCYZ.cyz_requestGet('/Index/getTopConfig', {}, function (xyz_data) {
                    wx.hideToast();
                    console.log(xyz_data)
                    if (xyz_data.code == 1) {
                        if (xyz_data.info.top_rule.length) {
                            const rule = xyz_data.info.top_rule[0];
                            that.setData({ top_day: rule.day, 
                            top_amount: rule.amount,
                            });
                        }
                        that.setData({
                            this_top_config: xyz_data.info, this_jinbi_pay_open: xyz_data.info.is_jinbi_pay,
                            is_hongbao_open: xyz_data.info.is_hongbao_open});
                    } else {
                        _functionCYZ.CYZ_alert(xyz_data.info, "/pages/info/index", "tab");
                    }
                });
            } else {
                _functionCYZ.CYZ_alert(xyz_data.info, "/pages/info/index", "tab");
            }
        });
    },
    info_formSubmit: function (e) {
        var that = this;
		if (that.data.mianze_is_check == false) {
			_functionCYZ.CYZ_alert('请先阅读并同意免责声明');
			return false;
		}
        that.setData({ btn_submit_disabled: true, submitIsLoading: true });
        _functionCYZ.CYZ_loading_n("发布中，请稍候...");
        var requestData = e.detail.value;
        requestData.cate_id = that.data.this_cate_id;
        requestData.u_province = that.data.this_u_province;
        requestData.u_city = that.data.this_u_city;
        requestData.u_district = that.data.this_u_district;
        wx.setStorageSync('servers_mobile', requestData.mobile);
        _requsetCYZ.cyz_requestPost('/Info/infoAdd', requestData, function (xyz_data) {
            wx.hideLoading();
            if (xyz_data.code == 1) {
                //开始上传图片
                that.submit_upload_pic(xyz_data.info);
            } else if (xyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.info_formSubmit(e);
                });
                return false;
            } else {
                that.setData({ btn_submit_disabled: false, submitIsLoading: false });
                _functionCYZ.CYZ_alert(xyz_data.info);
                return false;
            }
        });
    },
    onOpenMapTap: function (e) {
        var that = this;
        wx.chooseLocation({
            success: (res) => {
                qqmapsdk.reverseGeocoder({
                    location: {
                        latitude: res.latitude,
                        longitude: res.longitude
                    },
                    success: (res) => {
                        res = res.result;
                        that.setData({
                            this_u_province: res.address_component.province,
                            this_u_city: res.address_component.city,
                            this_u_district: res.address_component.district,
                            address: res.address,
                            latitude: res.location.lat,
                            longitude: res.location.lng
                        });
                    }
                });
            }
        });
    },
    //删除图片
    del_pic_bind: function (e) {
        var that = this
        var index = e.currentTarget.id;
        var datas = that.data.postimg;
        datas.splice(index, 1)
        that.setData({
            postimg: datas
        })
    },
    //上传图片
    chooseimg_bind: function () {
        var that = this;
        var img_lenth = that.data.postimg.length;
        var sheng_count = that.data.img_count_limit - img_lenth;
        if (sheng_count <= 0) {
            wx.showModal({
                title: '提示',
                content: '对不起，最多可上传' + that.data.img_count_limit + '张图片',
                showCancel: false
            })
            return false
        }
        wx.chooseImage({
            count: sheng_count,
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    postimg: that.data.postimg.concat(res.tempFilePaths)
                });
            }
        })
    },
    //上传图片
    submit_upload_pic: function (info_data) {
        var that = this;
        var g_data = that.data.postimg;
        if (g_data.length > 0) {
            that.setData({ this_img_max: g_data.length });
            _functionCYZ.CYZ_loading('请稍候');
            that.imgUploadTime(info_data);
        } else {
            that.doPayInfo(info_data);
        }
    },
    imgUploadTime: function (info_data) {
        var that = this
        var this_img_len = that.data.this_img_i;
        var this_img_max_len = that.data.this_img_max;
        if (this_img_len < this_img_max_len) {
            var requsetData = {};
            requsetData.info_id = info_data.info_id;
            _requsetCYZ.cyz_uploadPic('/Info/uploadInfoPic', that.data.postimg[this_img_len], requsetData, function (cdata) {
                that.setData({ this_img_i: that.data.this_img_i + 1 });
                that.imgUploadTime(info_data);
            });
        } else {
            that.setData({ postimg: [], this_img_i: 0, this_img_max: 0 });
            wx.hideToast();
            that.doPayInfo(info_data);
        }
    },

    onTopDayChange: function (e) {
        const rules = this.data.this_top_config.top_rule, index = parseInt(e.detail.value);
        if (rules.length == 0) return;
        this.setData({ top_day: rules[index].day, top_amount: rules[index].amount });
    },

    onIsTopChange: function (e) {
        this.setData({ is_top: e.detail.value ? 1 : 0 });
    },

    doPayInfo: function (info_data) {
        var that = this;
        if (info_data.is_pay == 0 && info_data.pay_amount > 0) {
            if (that.data.this_jinbi_pay_open == 1){
                //显示余额支付
                wx.showActionSheet({
                    itemList: ['金币支付', '微信支付'],
                    success: (res) => {
                        if (res.tapIndex == 0) {
                            that.go_jinbi_pay_bind(info_data.info_id);
                        } else if (res.tapIndex == 1) {
                            //微信支付
                            that.go_pay_bind(info_data.info_id);
                        }
                    }, fail: () => {
                        //跳转我的发布
                        wx.redirectTo({ url: 'my-lists', });
                    }
                });
                return false;
            }else{
                //微信支付
                that.go_pay_bind(info_data.info_id);
                return false;
            }
            
        } else if (info_data.info_status == 0) {
            _functionCYZ.CYZ_alert('信息发布成功，请等待客服审核', '/pages/info/index', 'tab');
        } else {
            //设置首页自动刷新
            wx.setStorageSync('index_auto_loading', 1);
            _functionCYZ.CYZ_alert('信息发布成功', '/pages/info/index', 'tab');
        }
    },
    go_pay_bind: function (info_id) {
        var that = this;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.info_id = info_id;
        _requsetCYZ.cyz_requestGet('/Info/infoPay', requestData, function (xyz_data) {
            wx.hideToast();
            if (xyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.go_pay_bind(info_id);
                });
            } else if (xyz_data.code == 1) {
                wx.requestPayment({
                    'timeStamp': xyz_data.info.timeStamp,
                    'nonceStr': xyz_data.info.nonceStr,
                    'package': xyz_data.info.package,
                    'signType': 'MD5',
                    'paySign': xyz_data.info.paySign,
                    'success': function (res) {
                        wx.setStorageSync('index_auto_loading', 1);
                        _functionCYZ.CYZ_alert('信息发布成功', '/pages/info/index', 'tab');
                    },
                    'fail': function (res) {
                        wx.setStorageSync('index_auto_loading', 1);
                        _functionCYZ.CYZ_alert('支付失败，请稍后在我的信息中可继续支付', '/pages/info/index', 'tab');
                    }
                })
            } else {
                _functionCYZ.CYZ_alert(xyz_data.info);
                return false;
            }
        });
    },
	go_jinbi_pay_bind: function (info_id) {
        var that = this;
        _functionCYZ.CYZ_loading();
        var requestData = {};
        requestData.info_id = info_id;
        _requsetCYZ.cyz_requestGet('/Info/infoJinbiPayJinbi', requestData, function (xyz_data) {
            wx.hideToast();
            if (xyz_data.code == 2) {
                app.getUserDataToken(function (token) {
                    that.go_jinbi_pay_bind(info_id);
                });
            } else if (xyz_data.code == 1) {
                wx.setStorageSync('index_auto_loading', 1);
                _functionCYZ.CYZ_alert('信息发布成功', '/pages/info/index', 'tab');
            } else {
				_functionCYZ.CYZ_alert(xyz_data.info, '/pages/info/index', 'tab');
                return false;
            }
        });
    },
	//免责
	radioChange:function(e){
		if (this.data.mianze_is_check == false){
			this.setData({ mianze_is_check: true });
		}else{
			this.setData({ mianze_is_check: false });
		}
	},
	go_mianze_info_bind:function(){
		wx.navigateTo({ url: "/pages/about/index?page_type=shengming" });
	},
    /**
	 * 设置值
	 */
    onSetValueTap: function (e) {
        const dataset = e.currentTarget.dataset, name = dataset.name, value = dataset.value;
        const data = {};
        data[name] = value;
        this.setData(data);
    },
})